package com.huel.fragment;

import android.app.Dialog;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.huel.bean.Btn;
import com.huel.bean.Goods;
import com.huel.bean.Item;
import com.huel.components.MyRecyclerViewAdapter;
import com.huel.components.RecyclerItemClickListener;
import com.huel.components.RushBuyCountDownTimerView;
import com.huel.components.ShowGoodsRecycleViewAdapter;
import com.huel.components.TextSwitchView;
import com.huel.dao.ItemsDao;
import com.huel.service.GetUtils;
import com.huel.taobaostore.GlideImageLoader;
import com.huel.taobaostore.MainActivity;
import com.huel.taobaostore.R;
import com.huel.taobaostore.ShowActivity;
import com.youth.banner.Banner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Index_Fragment extends Fragment {
    List<String> images = new ArrayList<>();
    List<Goods> goods = new ArrayList<>();
    private ShowGoodsRecycleViewAdapter recycleViewAdapter;
    private View contextView;
    private RushBuyCountDownTimerView timerView;
    private RecyclerView recyclerView, showGoods;
    private List<Btn> list = new ArrayList<>();
    private MyRecyclerViewAdapter myAdapte1r;
    private TextView username;
    private ImageView item2, item3, item6;
    private ItemsDao dao;
    private String data;

    public Index_Fragment() {

    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //请求网络数据
        images.add("https://img-bss.csdn.net/1603119499185.jpg");
        images.add("https://img.alicdn.com/imgextra/i1/6000000004482/O1CN013h31Jt1iynnYYc2Lg_!!6000000004482-0-octopus.jpg");
        images.add("https://img.alicdn.com/simba/img/TB18X1VSoY1gK0jSZFMSuuWcVXa.jpg");
        dao = new ItemsDao(getActivity());
    }

    // 创建view   也可以直接在这里面获取view中的控件。
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        contextView = inflater.inflate(R.layout.fragment_index, container, false);
        init();
        //更换城市信息
        changeCity();
        addCart();
        asynchronous();
        return contextView;
    }

    // 创建view完毕  可以直接在onCreateView中获取view中控件。
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //获取控件
        System.out.println("onCreated");
    }

    //初始化布局
    public void init() {
        Banner banner = (Banner) contextView.findViewById(R.id.banner);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //banner设置方法全部调用完毕时最后调用
        banner.start();

        TextSwitchView tsv = contextView.findViewById(R.id.tsv);
        String[] res = {
                "菜鸟官方推荐--双11的快递公司你选好了吗？",
                "你的iPhone12到货了吗",
                "iPhone 12系列蓝色最火，最高加价一千块",
                "HUAWEI P40 全时超清画质 超感知徕卡三摄",
                "HUAWEI Mate 30系列5G  重构想象"
        };
        tsv.setResources(res);
        tsv.setTextStillTime(3000);
        timerView = contextView.findViewById(R.id.timerView);
        // 设置时间(hour,min,sec)
        timerView.setTime(10, 0, 10);
        // 开始倒计时
        timerView.start();
        //使用recycleView 实现网格布局滚动
        recyclerView = contextView.findViewById(R.id.rlv);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 5);
        list.add(new Btn("天猫", R.mipmap.tianmao));
        list.add(new Btn("直播", R.mipmap.zhibo));
        list.add(new Btn("充值", R.mipmap.chongzhi));
        list.add(new Btn("爆款", R.mipmap.baokuang));
        list.add(new Btn("客服", R.mipmap.kefu));
        list.add(new Btn("物流", R.mipmap.wuliu));
        list.add(new Btn("发现", R.mipmap.faxian));
        list.add(new Btn("金币", R.mipmap.jinbi));
        list.add(new Btn("红包", R.mipmap.hongbao));
        list.add(new Btn("卡券", R.mipmap.kaquan));
        myAdapte1r = new com.huel.components.MyRecyclerViewAdapter(list);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(myAdapte1r);
        //展示商品的recycleView
        showGoods = contextView.findViewById(R.id.goodsRlv);
        recycleViewAdapter = new ShowGoodsRecycleViewAdapter(goods);
        //瀑布流布局
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        showGoods.setLayoutManager(staggeredGridLayoutManager);
        showGoods.setAdapter(recycleViewAdapter);
        //       添加商品到购物车
    }

    /**
     * 异步请求 商品信息 数据
     */
    public void asynchronous() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.199.229:8080/Android_war_exploded/cakeServlet?action=list")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失败回调
                System.out.println("请检查网络");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                String json = response.body().string();//注意response.body().string() 只能调用一次！
                //响应成功,这个回调在子线程中,所以不需要创建线程
                if (response.isSuccessful()) {
                    //isSuccessful方法：如果代码位于（200…300）中，则返回true，这意味着请求已成功接收
                    System.out.println("请求网络Ok");
                    try {
                        goods.clear();
                        JSONArray jsonArray = new JSONArray(json);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            if (jsonObject != null) {
                                int id = jsonObject.optInt("id");
                                String name = jsonObject.optString("name");
                                double price = jsonObject.optDouble("price");
                                String details = jsonObject.optString("details");
                                String imagePath = jsonObject.optString("pic");
                                // 封装Java对象
                                Goods good = new Goods(id, name, price, imagePath, details);
                                System.out.println("网络地址：" + good.getPic());
                                goods.add(good);
                                //添加到类中
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    //在这写  更新UI操作

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            recycleViewAdapter.setmList(goods);
                            recycleViewAdapter.notifyDataSetChanged();
                        }
                    });


                }
            }
        });
    }

    //更改城市信息
    public void changeCity() {
        contextView.findViewById(R.id.cityBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                View view01 = LayoutInflater.from(getActivity()).inflate(R.layout.activity_location_dialog, null);
                TextView cancel = view01.findViewById(R.id.choosepage_cancel);
                TextView sure = view01.findViewById(R.id.choosepage_sure);
                final EditText edittext = view01.findViewById(R.id.choosepage_edittext);
                final Dialog dialog = builder.create();
                dialog.show();
                dialog.getWindow().setContentView(view01);
                //使editext可以唤起软键盘
                dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "cancel", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
                sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(), "sure", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                });
            }


        });

    }


    //添加商品到购物车

    public void addCart() {
        showGoods.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                把对象通过 get set 方法 传输给 其他 fragment 中传给购物车页面
                //速成办法 无对象式购物车  请求网络服务
//                queryDialog(goods.get(position));
                //首先我能获取到 商品信息 将商品信息传给 一个Activity
                Intent intent = new Intent(getActivity(), ShowActivity.class);
                intent.putExtra("goods", goods.get(position));
                startActivity(intent);
            }
        }));
    }

    public void show(String information) {
        Toast.makeText(getActivity(), information, Toast.LENGTH_SHORT).show();
    }




}
